﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace TorchView.Game
{
    /// <summary>
    /// A torchlight shared stash file
    /// </summary>
    public sealed class SharedStash
    {
        const string GAME_BACKUP_EXT = "bak";

        public string Filename { get; private set; }

        public uint FileVersion { get; set; }
        public Item[] Items { get; set; }

        /// <summary>
        /// Load a Torchlight shared stash file
        /// </summary>
        /// <param name="filename">shared stash file</param>
        /// <returns>The shared stash for the file</returns>
        public static SharedStash Load(string filename)
        {
            SharedStash stash = new SharedStash { Filename = filename };
            BinaryReader reader = null;
            try
            {
                reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
                stash.FileVersion = reader.ReadUInt32();
                ReadItems(stash, reader);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
            return stash;
        }

        private static void ReadItems(SharedStash stash, BinaryReader reader)
        {
            int itemCount = reader.ReadInt32();
            if (itemCount < 0)
                itemCount = 0;
            Item[] items = new Item[itemCount];
            for (int i = 0; i < itemCount; i++)
                items[i] = Item.Read(reader);
            stash.Items = items;
        }

        public void Save(string filename)
        {
            if (filename == null)
                throw new ArgumentNullException("filename");

            BinaryWriter output = null;
            try
            {
                output = new BinaryWriter(new FileStream(filename, FileMode.Create, FileAccess.ReadWrite));
                output.Write(FileVersion);
                output.Write(Items.Length);
                foreach (Item item in Items)
                {
                    item.Write(output);
                }
            }
            finally
            {
                if (output != null)
                    output.Close();
            }
        }
    }
}
